package com.gin.kotlin.vegetables_kot.adapter

import android.content.DialogInterface
import android.content.Intent
import android.view.View
import androidx.activity.result.ActivityResultLauncher
import androidx.fragment.app.FragmentActivity
import com.gin.kotlin.vegetables_kot.R
import com.gin.kotlin.vegetables_kot.app.App
import com.gin.kotlin.vegetables_kot.base.AbstractBindingRecyclerViewAdapter
import com.gin.kotlin.vegetables_kot.base.AlertDialogUtils
import com.gin.kotlin.vegetables_kot.base.MyHandler
import com.gin.kotlin.vegetables_kot.base.PhotoPreviewUtils
import com.gin.kotlin.vegetables_kot.databinding.ItemVegRecordBinding
import com.gin.kotlin.vegetables_kot.enums.MsgWhat
import com.gin.kotlin.vegetables_kot.network.response.body.VegRecord
import com.gin.kotlin.vegetables_kot.network.response.common.Res
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import java.time.ZoneId
import java.time.ZonedDateTime
import java.time.format.DateTimeFormatter

class VegRecordAdapter(val activity: FragmentActivity, handler: MyHandler, val launcher: ActivityResultLauncher<Intent>) :
    AbstractBindingRecyclerViewAdapter<ItemVegRecordBinding, VegRecord>(activity, handler), View.OnClickListener {
    val api = App.INSTANCE.vegRecordApi
    override fun onBindViewHolder(
        holder: ViewHolder<ItemVegRecordBinding>,
        position: Int,
        b: ItemVegRecordBinding,
        dataModel: VegRecord
    ) {
        b.tvPosition.text = dataModel.position
        b.tvDescription.text = dataModel.description
        b.tvTypeO.text = dataModel.typeO
        b.tvTypeV.text = dataModel.typeV

        b.tvTimeR.text = formatTime(dataModel.timeR)
        b.tvTimeO.text = formatTime(dataModel.timeO)?.let { "操作: $it" }

        b.tvImages.also { tv ->
            tv.visibility = if (dataModel.images.isNullOrEmpty()) View.GONE else View.VISIBLE
            tv.text = "(${dataModel.images?.size ?: 0})"
        }

        listOf(b.tvImages,b.tvDelete,b.tvEdit,b.tvUpload).forEach { tv->
            tv.tag = dataModel
            tv.setOnClickListener (this)
        }
    }

    override fun onClick(v: View?) {
        val record = v?.tag as? VegRecord ?: return
        val index = data.indexOf(record)
        println("v.id = ${v.id}")
        when (v.id) {
            // 编辑
            R.id.tv_edit->handler.sendMessage(MsgWhat.VEG_RECORD_UPDATE, record)
            // 上传，选择文件
            R.id.tv_upload -> {
                handler.sendMessage(MsgWhat.VEG_RECORD_UPLOAD,record.uuid)
                launcher.launch(Intent().also {
                    it.action = Intent.ACTION_GET_CONTENT
                    it.type = "*/*"
                })
            }
            // 预览图片
            R.id.tv_images -> PhotoPreviewUtils.build(
                activity,
                record.images!!.map { "http://47.102.208.73:16666/images/${it.path}" }
            ) { position, _, _ ->
                // 长按删除图片
                val image = record.images!![position]
                AlertDialogUtils.builder(
                    context,
                    "删除图片",
                    listener = { _, which ->
                        if (which == DialogInterface.BUTTON_POSITIVE) api.delImage(image.uuid!!).enqueue(object : Callback<Res<Nothing>?> {
                            override fun onResponse(call: Call<Res<Nothing>?>, response: Response<Res<Nothing>?>) {
                                response.body()?.message?.also { handler.toast(it) }
                                if (response.code() == 200) record.images?.removeAt(position)
                            }

                            override fun onFailure(call: Call<Res<Nothing>?>, t: Throwable) {
                                AlertDialogUtils.builder(context, "请求错误", t.localizedMessage).show()
                            }
                        })
                    }).show()
                true
            }.build().show()

            R.id.tv_delete -> AlertDialogUtils.builder(
                context,
                "删除记录",
                listener = { _, which ->
                    if (which == DialogInterface.BUTTON_POSITIVE) api.del(record.uuid!!).enqueue(object : Callback<Res<Nothing>?> {
                        override fun onResponse(call: Call<Res<Nothing>?>, response: Response<Res<Nothing>?>) {
                            response.body()?.message?.also { handler.toast(it) }
                            removeData(index)
                        }

                        override fun onFailure(call: Call<Res<Nothing>?>, t: Throwable) {
                            AlertDialogUtils.builder(context, "请求错误", t.localizedMessage).show()
                        }
                    })
                }).show()
        }
    }

    companion object {
        private val SIMPLE_DATE_TIME_FORMATTER: DateTimeFormatter =
            DateTimeFormatter.ofPattern("yy-MM-dd HH:mm")

        fun formatTime(zdt: ZonedDateTime? = null) =
            zdt?.let { SIMPLE_DATE_TIME_FORMATTER.format(it.withZoneSameInstant(ZoneId.systemDefault())) }
    }

}